import { Component, OnInit, ViewChild } from '@angular/core';
import { NavController, Slides } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { Socket } from 'ng-socket-io';
import { ChatRoomPage } from '../chat-room/chat-room';

import { Observable,Subscription } from 'rxjs';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Slides) slides: Slides;


  user: any;

  items: any = [];

  // no list
  noList: boolean = false;

  listenEvent:Subscription;
  constructor(public navCtrl: NavController, public socket: Socket) {

    let _user = localStorage.getItem('user');

    if (_user) {
      this.user = JSON.parse(_user);

      this.listenEvent = this.getChatList().subscribe((data)=>{
        console.log(data);
      });
    } else {
      this.navCtrl.push(LoginPage);
    }
  }

  // joinChat() {
  //   this.socket.connect();
  //   this.socket.emit('set-nickname', this.nickname);
  //   this.navCtrl.push(ChatRoomPage, { nickname: this.nickname });
  // }

  goLogin(){
    console.log('go');
    this.navCtrl.push(LoginPage);
  }

  // search
  searchItem(data) {
    console.log(data);
  }

  // lists
  getChatList() {
    this.socket.connect();
    this.socket.emit('init', this.user);
    this.socket.emit('getChaterlist', this.user);

    let observable = new Observable(observer => {
      this.socket.on('chatListBack', (data) => {
        observer.next(data);
      });
    })
    return observable;
  }

  ionViewWillLeave(){
    if(this.listenEvent){
      this.listenEvent.unsubscribe();
    }
    
  }




}
